﻿using Digitalmes.Model;
using Digitalmes.Model.FactoryManagement;
using Digitalmes.Model.PlanningManagement;
using Digitalmes.ViewModel.PlanningManagement.ProductionPlanningVMs;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Extensions;
using WalkingTec.Mvvm.Mvc;

namespace Digitalmes.PlanningManagement.Controllers
{
    [AuthorizeJwtWithCookie]
    [ActionDescription("_Model.ProductionPlanning")]
    [ApiController]
    [Route("/api/PlanningManagement/ProductionPlanning")]
    public partial class ProductionPlanningController : BaseApiController
    {
        EncodeService EncodeService {  get; set; }      
        public ProductionPlanningController(EncodeService encode)
        {
            EncodeService = encode; 
        }

        [ActionDescription("Sys.Get")]
        [HttpGet("{id}")]
        public IActionResult Get(string id)
        {
            var vm = Wtm.CreateVM<ProductionPlanningVM>(id);
            return Ok(vm);
        }

        [ActionDescription("Sys.Create")]
        [HttpPost("[action]")]
        public async Task<IActionResult> Create(ProductionPlanningVM vm)
        {
            vm.Entity.Wo = await EncodeService.GenerateCodeBySchemeCodeAsync("ProductionPlanning");

            vm.Entity.PlanStatus = WoStatusEnum.Created;

            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                await vm.DoAddAsync();
   
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState.GetErrorJson());
                }
                else
                {
                    return Ok(vm.Entity);
                }
            }

        }

        [ActionDescription("Sys.Edit")]
        [HttpPut("[action]")]
        public async Task<IActionResult> Edit(ProductionPlanningVM vm)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                await vm.DoEditAsync(false);
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState.GetErrorJson());
                }
                else
                {
                    return Ok(vm.Entity);
                }
            }
        }


        [AllRights]
        [HttpPut("[action]")]
        public async Task<IActionResult> ToOrder(long id)
        {
            using (var trans = await Wtm.DC.Database.BeginTransactionAsync())
            {

                try
                {
                    var plan = DC.Set<ProductionPlanning>().CheckID(id).FirstOrDefault();
                    plan.PlanStatus = WoStatusEnum.Scheduled;
                    DC.Set<ProductionPlanning>().Update(plan);

                    var porder = new ProductionOrder();
                    porder.Sort = 1;
                    porder.PlanQty = plan.PlanQty.Value;

                    porder.PlanStartTime = plan.PlanStartTime;
                    porder.PlanEndTime = plan.PlanEndTime;
                    porder.Wo = plan.Wo;
                    porder.IsValid = true;
                    porder.OrderStatus = plan.PlanStatus.Value;
                    porder.ProductId = plan.ProductId;
                    porder.OrderSource = WoSourceEnum.Local;
                    porder.PlanId = plan.ID;
                    var neworder= DC.Set<ProductionOrder>().Add(porder);

                    await DC.SaveChangesAsync();

                    await trans.CommitAsync();

                    return Ok(plan);

                }
                catch (Exception ex)
                {

                    trans.Rollback();
                }


            }
            return BadRequest();
        }




        [HttpPost("BatchEdit")]
        [ActionDescription("Sys.BatchEdit")]
        public ActionResult BatchEdit(ProductionPlanningBatchVM vm)
        {
            if (!ModelState.IsValid || !vm.DoBatchEdit())
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                return Ok(vm.Ids.Count());
            }
        }

		[HttpPost("BatchDelete")]
        [ActionDescription("Sys.Delete")]
        public IActionResult BatchDelete([FromBody] string[] ids)
        {
            var vm = Wtm.CreateVM<ProductionPlanningBatchVM>();
            if (ids != null && ids.Count() > 0)
            {
                vm.Ids = ids;
            }
            else
            {
                return Ok();
            }
            if (!ModelState.IsValid || !vm.DoBatchDelete())
            {
                return BadRequest(ModelState.GetErrorJson());
            }
            else
            {
                return Ok(ids.Count());
            }
        }

        [ActionDescription("Sys.DownloadTemplate")]
        [HttpGet("GetExcelTemplate")]
        public IActionResult GetExcelTemplate()
        {
            var vm = Wtm.CreateVM<ProductionPlanningImportVM>();
            var qs = new Dictionary<string, string>();
            foreach (var item in Request.Query.Keys)
            {
                qs.Add(item, Request.Query[item]);
            }
            vm.SetParms(qs);
            var data = vm.GenerateTemplate(out string fileName);
            return File(data, "application/vnd.ms-excel", fileName);
        }

        [ActionDescription("Sys.Import")]
        [HttpPost("Import")]
        public ActionResult Import(ProductionPlanningImportVM vm)
        {

            if (vm.ErrorListVM.EntityList.Count > 0 || !vm.BatchSaveData())
            {
                return BadRequest(vm.GetErrorJson());
            }
            else
            {
                return Ok(vm.EntityList.Count);
            }
        }

        [Public]
        [HttpGet("GetProductionLines")]
        public ActionResult GetProductionLines()
        {
            return Ok(DC.Set<ProductionLine>().GetSelectListItems(Wtm, x => x.Name));
        }

        [Public]
        [HttpGet("GetProductionLineProducts")]
        public ActionResult GetProductionLineProducts(long id)
        {
            return Ok(DC.Set<ProductProductionLine>().Include(x=>x.Product).CheckID(id).GetSelectListItems(Wtm, x => x.Product.Name));
        }


        [Public]
        [HttpGet("GetProductionLineShifts")]
        public ActionResult GetProductionLineShifts(long id)
        {
            return Ok(DC.Set<LineShift>().CheckID(id,x=>x.LineId).GetSelectListItems(Wtm, x => x.Name));
        }


    }
}